package com.woniuxy.auth.controller;

import com.woniuxy.commons.entity.User;
import com.woniuxy.commons.enums.ResultEnum;
import com.woniuxy.commons.util.JwtUtil;
import com.woniuxy.commons.util.ResponseResult;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/auth")
public class AuthController {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @PostMapping("/login")
    public ResponseResult login(@RequestBody User user, HttpServletResponse response){

        String token = JwtUtil.generateToken(user.getAccount());
        //刷新token
        String refreshtoken = UUID.randomUUID().toString();

        /*
        * 将token和refreshtoken放到redis
        * refreshtoken作为key，account和token作为value
        * */
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        map.put("account",user.getAccount());
        //refreshtoken作为key，map为value
        //redisTemplate.opsForValue().set(refreshtoken,map);
        //redisTemplate.expire(refreshtoken,30, TimeUnit.DAYS);  //过期时间

        //将token和refreshtoken返回给前端
        response.setHeader("authorization",token);
        response.setHeader("refreshtoken",refreshtoken);
        //暴露头
        response.setHeader("Access-Control-Expose-Headers","authorization,refreshtoken");
        //response.setHeader("Access-Control-Expose-Headers","refreshtoken");
        return null;
    }
    /*
    * 从拦截器接受account、perms，查询数据库权限对比
    * */
    @GetMapping("/perms/{account}/{perms}")
    public ResponseResult existPerms(@PathVariable(value = "account") String account,@PathVariable(value = "perms")String perms){
        //查表得权限信息
        //假设得到了当前用户所有的权限信息
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(200);
        responseResult.setStatus(ResultEnum.PERMS_NO); //默认为no
        responseResult.setMessage("你没有权限！");
        List<String> permsList = Arrays.asList("goods:all","goods:del","goods:update");
        if (permsList.contains(perms)){
            responseResult.setMessage("当前用户"+account+"拥有"+perms+"权限");
            responseResult.setStatus(ResultEnum.PERMS_YES);
        }
        //
        return responseResult;
    }
}
